import {Body, Controller,Ctx,Get, Header, Params, Post, Query} from "koa-ts-controllers";
import { IsNotEmpty, IsNumberString } from "class-validator";
import Boom from "@hapi/Boom";
import { Context } from "koa";

class GetUsersQuery{
    @IsNumberString()
    page: number
}

class PostUserBody{
    @IsNotEmpty({
        message:"用户名不能为空"
    })
    name:String

    @IsNotEmpty({
        message:"密码不能为空"
    })
    password:String
}

@Controller("/test")
class TestController{

    @Get("/hello")
    async hello(a:any){
        console.log(a.b);
        
        return "hello test!"
    }

    @Get("/user/:id(\\d+)")
    async getUser(@Params("id") id:number){
    // async getUser(@Params() p:{id:number}){
        return "当前params的id是："+id
    }

    @Get("/user")
    async getUser2(@Query() q:{id:number}){
        // async getUser(@Params() p:{id:number}){
        return "当前Query的id是："+q.id
    }

    @Post("/user")
    async postUser(
        @Ctx() ctx:Context,
        @Body() body: PostUserBody,
        @Header() h:any
    ){
        console.log(h);
        ctx.status = 201;
        
        return "当前提交的数据是："+JSON.stringify(body) 
    }

    @Get("/users")
    async getUsers(
        @Query() q: GetUsersQuery
    ){
        console.log(q);
        // 用户不存在，用户被注册
        if(true){
            throw Boom.notFound("注册失败","用户名已经被注册了");
        }

        return "传过来的query:"+JSON.stringify(q)
    }
}